"use client";

import React, { HTMLAttributes, useEffect, useState } from "react";
import { useTRPCClient } from "@server/trpc/client";
import { TRPCClientError } from '@trpc/client';
import { Card, Spin, Alert, TableProps } from '@arco-design/web-react';
import { PathNavigation, DriveList, FileTable } from './components';
import { TableData } from "./components/FileTable";

type Props = {
  tableProps?: TableProps<TableData>,
} & HTMLAttributes<HTMLDivElement>

const FileManager: React.FC<Props> = ({ tableProps, ...divProps }) => {
  // 使用TRPC客户端钩子
  const trpc = useTRPCClient();
  
  // 当前路径状态
  const [currentPath, setCurrentPath] = useState<string>("");
  // 文件列表状态
  const [files, setFiles] = useState<any[]>([]);
  // 驱动器列表状态
  const [drives, setDrives] = useState<string[]>([]);
  // 加载状态
  const [loading, setLoading] = useState<boolean>(false);
  // 错误状态
  const [error, setError] = useState<string | null>(null);

  // 获取驱动器列表
  const getDrives = trpc.fileManager.getDrives.query;

  // 获取目录内容
  const getDirectoryContents = trpc.fileManager.getDirectoryContents.query;

  // 打开文件
  const openFile = trpc.fileManager.openFile.mutate;

  // 更新驱动器列表
  useEffect(() => {
    const fetchDrives = async () => {
      try {
        setLoading(true);
        const driveData = await getDrives();
        setDrives(driveData);
        // 如果当前路径为空且有驱动器，设置默认路径为第一个驱动器
        if (currentPath === "" && driveData.length > 0) {
          setCurrentPath(driveData[0]);
        }
      } catch (err) {
        setError(`无法获取驱动器列表: ${err instanceof Error ? err.message : '未知错误'}`);
      } finally {
        setLoading(false);
      }
    };

    fetchDrives();
  }, []);

  // 更新目录内容
  useEffect(() => {
    const fetchDirectoryContents = async () => {
      if (currentPath !== "") {
        try {
          setLoading(true);
          const directoryData = await getDirectoryContents({ path: currentPath });
          setFiles(directoryData);
        } catch (err) {
          setError(`无法获取目录内容: ${err instanceof Error ? err.message : '未知错误'}`);
        } finally {
          setLoading(false);
        }
      }
    };

    fetchDirectoryContents();
  }, [currentPath]);

  // 处理文件夹点击
  const handleFolderClick = (folderName: string) => {
    // 确保路径以反斜杠结尾，并正确拼接文件夹名
    let newPath = currentPath;
    if (!newPath.endsWith("\\")) {
      newPath += "\\";
    }
    newPath += folderName + "\\";
    // 确保没有重复的反斜杠
    newPath = newPath.replace(/\\\\+/g, "\\");
    console.log(newPath);
    
    setCurrentPath(newPath);
  };

  // 处理文件点击
  const handleFileClick = (fileName: string) => {
    // 确保文件路径正确拼接
    let filePath = currentPath;
    if (!filePath.endsWith("\\")) {
      filePath += "\\";
    }
    filePath += fileName;
    // 确保没有重复的反斜杠
    filePath = filePath.replace(/\\\\+/g, "\\");
    
    openFile({ path: filePath })
      .then(() => {
        console.log("文件已打开:", filePath);
      })
      .catch((error: unknown) => {
        setError(`无法打开文件: ${error instanceof Error ? error.message : '未知错误'}`);
      });
  };

  // 处理返回上级目录
  const handleGoUp = () => {
    // 检查是否为驱动器根目录
    const isDriveRoot = drives.some(drive =>
      currentPath.toLowerCase() === drive.toLowerCase() ||
      currentPath.toLowerCase() === drive.toLowerCase().slice(0, -1)
    );

    if (!isDriveRoot) {
      // 移除最后一个路径部分
      const pathParts = currentPath.split("\\").filter(part => part !== "");
      if (pathParts.length > 1) {
        pathParts.pop();
        const newPath = pathParts.join("\\") + "\\";
        // 确保没有重复的反斜杠
        const normalizedPath = newPath.replace(/\\\\+/g, "\\");
        setCurrentPath(normalizedPath);
      } else if (pathParts.length === 1) {
        // 回到驱动器列表
        setCurrentPath("");
      }
    } else {
      // 如果是驱动器根目录，回到驱动器列表
      setCurrentPath("");
    }
  };

  // 格式化文件大小
  const formatFileSize = (bytes: number): string => {
    if (bytes === 0) return "0 Bytes";
    const k = 1024;
    const sizes = ["Bytes", "KB", "MB", "GB"];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i];
  };

  return (
    <div {...divProps}>
      {error && (
        <Alert
          type="error"
          content={error}
          closable
          onClose={() => setError(null)}
          className="mb-4"
        />
      )}
      
      <PathNavigation
        currentPath={currentPath}
        drives={drives}
        onPathChange={setCurrentPath}
        onGoUp={handleGoUp}
        getDirectoryContents={getDirectoryContents}
        setError={setError}
      />
      
      {(currentPath === "") && (
        <DriveList
          drives={drives}
          onDriveSelect={setCurrentPath}
        />
      )}
      
      {(currentPath !== "") && (
        <FileTable
          {...tableProps}
          files={files}
          loading={loading}
          onFolderClick={handleFolderClick}
          onFileClick={handleFileClick}
          formatFileSize={formatFileSize}
        />
      )}
    </div>
  );
};

export default FileManager;